【问题标题】:Android : Activity button shows up on fragmentAndroid:活动按钮显示在片段上
【发布时间】:2020-12-03 19:23:41
【问题描述】:

我有一个简单的应用程序,其中一个 Activity 调用一个 Fragment。

我的问题是 .. 为什么 Activity 的按钮会显示在 Fragment 上?

似乎是一个非常简单的问题..只是无法确定问题!!

活动截图:

片段截图:

请注意,Activity 的 SUBMIT 按钮显示在 Fragment 上,但 TextView 和 EditText 被隐藏了。 为什么??

活动:

package com.example.deep_kulshreshtha.toddsyndrome;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private TextInputEditText inputEditText;
    private EditText editText;
    private ToddSyndromeDBHelper dbHelper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowHomeEnabled(true);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

//        inputEditText = (TextInputEditText) findViewById(R.id.lastNameEditText);
        editText = (EditText) findViewById(R.id.editText);

        Button submitButton = (Button) findViewById(R.id.submitButton);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CreateReportFragment fragment = CreateReportFragment.newInstance();

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.content_main, fragment, "CreateFragment");
                transaction.addToBackStack("CreateBackStack");
                transaction.commit();
            }
        });

        dbHelper = new ToddSyndromeDBHelper(this);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(db != null) {db.close();}
    }

    public SQLiteDatabase getDb(){

        if(db == null) {
//            new ConnectionHelper().execute();
            db = dbHelper.getWritableDatabase();
        }
        return db;
    }

    public void viewPatientReport(View view){

        PatientReportFragment fragment = PatientReportFragment.
                newInstance(editText.getText().toString());

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_main, fragment, "SearchFragment");
        transaction.addToBackStack("SearchBackStack");
        transaction.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class ConnectionHelper extends AsyncTask<Void, Void, SQLiteDatabase>{

        @Override
        protected SQLiteDatabase doInBackground(Void... params) {
            db = dbHelper.getWritableDatabase();
            return db;
        }
    }
}

活动 xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

内容 xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/headline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="32dp"
        android:fontFamily="cursive"
        android:text="@string/todd_syndrome" />

<!--    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_last_name"
        android:layout_below="@id/headline"
        android:layout_centerHorizontal="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/lastNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />
    </android.support.design.widget.TextInputLayout>-->

    <EditText
        android:id="@+id/editText"
        android:layout_below="@id/headline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_text_hint"/>

    <Button
        android:id="@+id/submitButton"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_below="@id/editText"
        android:onClick="viewPatientReport"/>

</RelativeLayout>

片段:

package com.example.deep_kulshreshtha.toddsyndrome;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class CreateReportFragment extends Fragment
        implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

//    private OnFragmentInteractionListener mListener;
    String name;
    boolean hallucegenicDrugs = false;
    int age;
    String gender;
    boolean migraine = false;

    private EditText editText;
    private Switch switchMigraine;
    private Spinner ageSpinner;
    private RadioGroup group;
    private Switch switchHall;
    private Button saveButton;

    private View.OnClickListener radioListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean checked = ((RadioButton)v).isChecked();
            gender = ((RadioButton)v).getText().toString();
        }
    };

    public CreateReportFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static CreateReportFragment newInstance(/*String param1, String param2*/) {
        CreateReportFragment fragment = new CreateReportFragment();
//        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
//        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
//            mParam1 = getArguments().getString(ARG_PARAM1);
//            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_create_report, container, false);

        editText = (EditText) view.findViewById(R.id.createPersonName);
        name = editText.getText().toString();

        switchMigraine = (Switch) view.findViewById(R.id.migraineToggle);
        switchMigraine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                migraine = false;
            }
        });

        ageSpinner = (Spinner) view.findViewById(R.id.ageSpinner);

        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= 100; i++){ list.add(i); }
        ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getContext(),
                android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        ageSpinner.setAdapter(adapter);
        ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                age = (int) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        group = (RadioGroup) view.findViewById(R.id.genderButton);

        RadioButton maleRadio = (RadioButton) view.findViewById(R.id.radioMale);
        maleRadio.setOnClickListener(radioListener);
        RadioButton femaleRadio = (RadioButton) view.findViewById(R.id.radioFemale);
        femaleRadio.setOnClickListener(radioListener);

        switchHall = (Switch) view.findViewById(R.id.switchButton);
        switchHall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                hallucegenicDrugs = isChecked;
            }
        });

        saveButton = (Button) view.findViewById(R.id.saveButton);
        saveButton.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        int syndromePercentage = 0;

        Log.v("Deep", "Patient name : " + name);
        Log.v("Deep", "Has migraine : " + migraine);
        Log.v("Deep", "Patient age : " + age);
        Log.v("Deep", "Patient gender : " + gender);
        Log.v("Deep", "Drugs ? : " + hallucegenicDrugs);

        if(migraine == true){ syndromePercentage += 25; }
        if(age <= 15){ syndromePercentage += 25; }
        if(gender.equals("Male")){ syndromePercentage += 25; }
        if(hallucegenicDrugs == true){ syndromePercentage += 25; }

        SQLiteDatabase db = ((MainActivity)getActivity()).getDb();

        ContentValues values = new ContentValues();
        values.put(PatientTableContract.FeedEntry.COL_NAME_PATIENT_NAME, name);
        values.put(PatientTableContract.FeedEntry.COL_NAME_RISK, syndromePercentage);

        db.insert(PatientTableContract.FeedEntry.TABLE_NAME, null, values);

        Toast.makeText(getContext(), "Data saved successfully !", Toast.LENGTH_SHORT).show();

        editText.setText("");
        switchMigraine.setChecked(false);
        ageSpinner.setSelection(0);
        group.clearCheck();
        switchHall.setChecked(false);
    }

}

片段 xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.CreateReportFragment"
    android:background="@android:color/white">

    <!-- TODO: Update blank fragment layout -->
    <android.support.design.widget.TextInputLayout
        android:id="@+id/nameLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/createPersonName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />

    </android.support.design.widget.TextInputLayout>

<!--    <TextView
        android:id="@+id/migraineText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/nameLayout"
        android:text="@string/hint1"/>-->

    <Switch
        android:id="@+id/migraineToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hint1"
        android:layout_below="@id/nameLayout"
        android:checked="false"
        android:layout_margin="10dp"
        android:padding="10dp" />

    <TextView
        android:id="@+id/ageText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/migraineToggle"
        android:text="@string/hint2"
        android:layout_margin="10dp"/>

    <Spinner
        android:id="@+id/ageSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:prompt="@string/hint2"
        android:layout_below="@id/migraineToggle"
        android:layout_toRightOf="@id/ageText"
        android:layout_margin="10dp"
        android:layout_marginLeft="20dp"/>

<!--    <TextView
        android:id="@+id/genderText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/ageText"
        android:text="@string/hint3"/>-->

    <RadioGroup
        android:id="@+id/genderButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@id/ageSpinner"
        android:checkedButton="@+id/radioMale"
        android:layout_margin="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gender ?"
            android:layout_margin="10dp"/>

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male"
            android:layout_margin="10dp"/>

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"
            android:layout_margin="10dp"/>
    </RadioGroup>

<!--    <TextView
        android:id="@+id/hallucinogenicText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/genderText"
        android:text="@string/hint4"/>

    <ToggleButton
        android:id="@+id/hallucinogenicToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/hallucinogenicText"
        android:hint="@string/hint4" />-->

    <Switch
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/genderButton"
        android:text="@string/hint4"
        android:checked="false"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/switchButton"
        android:text="Submit"
        android:layout_margin="10dp"/>

</RelativeLayout>

第二个片段 xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.PatientReportFragment"
    android:background="@android:color/white">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/patientReport"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="40dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</FrameLayout>

第二个片段:

package com.example.deep_kulshreshtha.toddsyndrome;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.deep_kulshreshtha.toddsyndrome.PatientTableContract.FeedEntry;


public class PatientReportFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private MainActivity activity;

    private String[] projection = {FeedEntry._ID, FeedEntry.COL_NAME_PATIENT_NAME,
            FeedEntry.COL_NAME_RISK};
    private String selection = FeedEntry.COL_NAME_PATIENT_NAME + " = ?";

//    private OnFragmentInteractionListener mListener;

    public PatientReportFragment() {
        // Required empty public constructor
    }

    public static PatientReportFragment newInstance(String param1) {
        PatientReportFragment fragment = new PatientReportFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        TextView textView = (TextView) view.findViewById(R.id.patientReport);

        SQLiteDatabase db = ((MainActivity)getActivity()).getDb();
        Cursor cursor = db.query(FeedEntry.TABLE_NAME,
                projection,
                selection,
                new String[]{mParam1},
                null,
                null,
                null);

        if(cursor.getCount() == 0){
            textView.setText("No data found");
            return /*view*/;
        } else {
            cursor.moveToFirst();
            int riskPercent = cursor.getInt(cursor.getColumnIndex(FeedEntry.COL_NAME_RISK));

            textView.setText("Risk percentage : " + riskPercent );
            return /*view*/;
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_patient_report, container, false);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

}

【问题讨论】:

  • 删除您的帖子不会将其从 stackoverflow 中删除,它只会取消发布,修复您的问题而不是删除它们
  • 嗨,艾哈迈德,不知道你的意思,但我没有尝试删除帖子。
  • 这里写的被删了
  • 这与您的 include 相关,因为您包含了它,所以您现在有 2 个按钮而不是一个,我想您应该将其从 context.xml 中删除并使其在布局中实际上需要它。或者您可以在需要它的活动中以编程方式制作它
  • @AhmedI.Elsayed :尝试将包含的 xml 放入 activity_main.xml。没用。

标签: android android-fragments android-activity


【解决方案1】:

我已经通过将我的按钮包装在 LinearLayout 中解决了这个问题。

问题的可能原因:似乎 Button 在 android 中具有更高的 z-index 渲染,因此不将其包装在另一个布局中会使该按钮高于所有其他片段。

<LinearLayout
    android:id="@+id/register_btn_wrapper"
    android:orientation="vertical"
    android:layout_below="@+id/splash_logo_img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/register_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/register"
        android:textSize="@dimen/text_big"
        android:paddingLeft="@dimen/btn_padding"
        android:paddingStart="@dimen/btn_padding"
        android:paddingRight="@dimen/btn_padding"
        android:paddingEnd="@dimen/btn_padding"
        android:layout_gravity="center"
        android:background="@color/app_color" />

</LinearLayout>

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    当你在片段中绑定你的视图时,在方法中绑定它总是一个更好的方法 onViewCreated() 当您在onCreateView() 中绑定视图时,您将面临渲染问题。 所以在onViewCreated()方法中绑定你的视图,问题应该就解决了

      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.name_of_layout,container,false);
        }
    
    
    
      public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
                super.onViewCreated(view, savedInstanceState);
            //bind your view here
        }
    

    【讨论】:

    • onViewCreated 在从onCreateView创建视图之后运行
    • 这就是为什么它总是返回 null
    • onViewCreated() 如果视图未正确膨胀,则返回 null。否则它可以正常工作,如果您在 onCreateView() @AhmedI.Elsayed 中绑定视图会出现问题
    • 这不会改变任何事情,顺便说一句,我想知道为什么我要查找代码顺序问题或其他什么
    • 据我所知,它的简单视图呈现问题。
    【解决方案3】:

    fragment的onCreateView中尝试加入这一行

        View view = inflater.inflate(R.layout.fragment_name, container, false);
        view.setBackgroundColor(Color.WHITE);
    

    我遇到了类似的问题,并使用上述行修复了它。另外,不要忘记将android:clickable="true" 添加到您的fragment_layout.xml 父布局中。

    【讨论】:

    • 我已经把这些放在了 xml 中。这没有用。 android:background="@android:color/white" android:clickable="true"
    • 尝试添加我在片段代码中指定的行,而不是在 XML 文件中。
    • 在 Fragment 中添加该行也不能解决问题。
    【解决方案4】:

    虽然我找不到这个问题的原因,但这里有一个小解决方法:

    更新以下布局并尝试:

    活动 xml:

    添加了框架布局:

     <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <include layout="@layout/content_main"/>
        </FrameLayout>
    

    在 MainActivity 中:使用 Framelayout 容器

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    CreateReportFragment fragment = CreateReportFragment.newInstance();
    
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(**R.id.container**, fragment, "CreateFragment");
                    transaction.addToBackStack("CreateBackStack");
                    transaction.commit();
                }
            });
    

    在 Content.xml 中添加了 android:layout_marginTop

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/content_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_marginTop="?attr/actionBarSize"
        tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
        tools:showIn="@layout/activity_main">
    

    在 fragment_create_report.xml 中添加了 android:layout_marginTop

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:background="@android:color/white">
    

    【讨论】:

      【解决方案5】:

      我不确定您是否还需要这方面的帮助。但基本上片段和活动必须在不同的布局中。

      这是它的一般结构:(您不必使用我在下面使用的特定布局)

      <RelativeLayout>
          <LinearLayout id="@+id/all_code_relevant_to_activity"></LinearLayout>
          <LinearLayout
              android:id="@+id/fragment_container"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
          </LinearLayout>
      </RelativeLayout>
      

      基本上,您希望将片段与其余代码分开。所以基本上你可以在Activity.xml 中围绕你的代码创建一个&lt;FrameLayout&gt;,然后在&lt;FrameLayout&gt; but outside &lt;android.support.design.widget.CoordinatorLayout&gt; 中自己添加你的片段布局。或者制作两个子布局,将它们分开

      【讨论】:

        【解决方案6】:

        在页面顶部只显示提交按钮非常简单。我想建议您使用add 片段而不是replace。之后请告诉我结果。

        FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.content_main, fragment, "SearchFragment");
        fragmentTransaction.addToBackStack("SearchFragment");
        fragmentTransaction.commitAllowingStateLoss();
        

        【讨论】:

        • 还是一样的结果!提交按钮显示在片段上。
        • @Deep 尝试在活动中初始化片段怎么样?
        • @KimKevin:我已经在 Activity 中初始化 Fragments 了:
        • 我明白你的意思.. 也会尝试。
        【解决方案7】:

        在您的活动 xml 中,再添加一个元素 FrameLayout 来承载片段,如下所示

        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/content_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
            tools:showIn="@layout/activity_main">
        
            <TextView
                android:id="@+id/headline"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:textSize="32dp"
                android:fontFamily="cursive"
                android:text="@string/todd_syndrome" />
        
        <!--    <android.support.design.widget.TextInputLayout
                android:id="@+id/layout_last_name"
                android:layout_below="@id/headline"
                android:layout_centerHorizontal="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
        
                <android.support.design.widget.TextInputEditText
                    android:id="@+id/lastNameEditText"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/edit_text_hint" />
            </android.support.design.widget.TextInputLayout>-->
        
            <EditText
                android:id="@+id/editText"
                android:layout_below="@id/headline"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/edit_text_hint"/>
        
            <Button
                android:id="@+id/submitButton"
                android:layout_centerHorizontal="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/submit"
                android:layout_below="@id/editText"
                android:onClick="viewPatientReport"/>
        
           <!-- new layout to host fragment -->
           <FrameLayout
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:id="@+id/fragment_holder"/>
        
        </RelativeLayout>
        

        并使用将您的 Fragment 添加到该 FrameLayout。

        【讨论】:

        • @Deep 你确定你将 Fragment 添加到了新添加的 FrameLayout 中,id 为 fragment_holder
        【解决方案8】:

        设置按钮属性android:translationZ="-3dp"会起作用。

        【讨论】:

          【解决方案9】:

          帮助我的是将android:translationZ="10dp" 添加到按钮上方的布局中

          【讨论】:

            猜你喜欢
            • 2020-09-27
            • 2012-07-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-13
            • 2011-12-18
            相关资源
            最近更新 更多