安卓:在片段上显示活动按钮

7
我是一名有用的助手,可以为您翻译文本。

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

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

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

Activity 截图:

enter image description here

片段截图:

enter image description here

请注意,Activity的提交按钮显示在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中删除它,它只会取消发布,修复您的问题而不是删除它们。 - Ahmed I. Elsayed
嗨,Ahmed,不确定你的意思是什么,但我没有尝试删除帖子。 - Deep
这里写着它已被删除。 - Ahmed I. Elsayed
这与你的 include 有关,因为你已经将它包含进来了,所以现在你有两个按钮而不是一个。我猜你应该从 context.xml 中删除它,并在实际需要它的布局中创建它。或者你可以在需要它的活动中以编程方式创建它。 - Ahmed I. Elsayed
@Deep,你找到解决问题的方法了吗? - Hudi Ilfeld
显示剩余2条评论
9个回答

3
我通过将按钮放置在LinearLayout中解决了这个问题。
该问题的可能原因是:在Android中,Button具有更高的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>

希望这可以帮到您。

1

当您在片段中绑定视图时,最好的方法是在方法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
    }

onViewCreatedonCreateView 创建视图后运行。 - Ahmed I. Elsayed
这就是为什么它总是返回 null。 - Ahmed I. Elsayed
如果视图未正确填充,则onViewCreated()会返回null。否则,它将正常工作,并且如果在onCreateView()中绑定视图,则可能会出现问题。@AhmedI.Elsayed - Satish Silveri
奇怪的是... TextView 和 EditText 都没问题,只有 Button 出了问题。 - Deep
@Deep 你是想要制作一个单一活动的应用程序吗? - Satish Silveri
显示剩余3条评论

1
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" - Deep
尝试将我在Fragment代码中指定的行添加到XML文件中而不是。 - Rajeev
在Fragment中添加这行代码也无法解决问题。 - Deep

1
我无法找到这个问题的原因,但是有一个小的解决方法:
更新以下布局并尝试:
Activity xml :
添加了一个Framelayout:
 <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">

1
我不确定您是否仍需要帮助。但基本上,碎片和活动必须位于不同的布局中。
这是一般的结构:(您不必使用下面我使用的特定布局)
<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中的代码周围制作一个<FrameLayout>,然后将片段布局单独放置在<FrameLayout>中,但在<android.support.design.widget.CoordinatorLayout>之外。 或者创建两个子布局并将它们分开。

0

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


0

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


0

只在页面顶部显示“提交”按钮真的很奇怪。我建议您使用添加片段而不是替换,请告诉我这样的结果如何。

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

依然是相同的结果!提交按钮出现在片段上。 - Deep
1
@Deep 你觉得在Activity中尝试初始化一个Fragment怎么样? - kimkevin
@KimKevin:我已经在Activity中初始化了Fragments。 - Deep
我明白你的意思了,我也会尝试一下。 - Deep

0
在你的 activity xml 中,添加一个名为 FrameLayout 的元素,用于承载 Fragment,如下所示。
<?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 添加到了新添加的 ID 为 fragment_holder 的 FrameLayout 中吗? - Anoop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接