簡體   English   中英

Android - 如何在 onCreate( ) 中膨脹 xml

[英]Android - How to inflate xml in onCreate( )

我只是盯着 Android 應用程序開發,並有一個關於在 MainActivity 的 onCreate() 中膨脹布局的問題。 可能是我沒有問正確的問題。 但基本上我有 2 個標簽。 我在第一個選項卡上有一個計算按鈕,點擊后應該會在第二個選項卡上填充一個表格

public class MainActivity extends AppCompatActivity {

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

        new MyTableFragment();

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

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Details"));
        tabLayout.addTab(tabLayout.newTab().setText("Discount"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        this.init();
    }
    public void onButtonClick(View view) {

        EditText text = (EditText) findViewById(R.id.amount);
        _amount = Integer.parseInt(text.getText().toString());

        text = (EditText) findViewById(R.id.rate);
        _rate = Integer.parseInt(text.getText().toString()) * 12;

        EditText discount = (EditText) findViewById(R.id.discount);
        discount.setText(Double.toString(_discount));

        this.init();
    }

    public void init(){
        TableLayout tableLayout = (TableLayout) findViewById(R.id.table_main);
        if(tableLayout == null)
            System.out.println("Table Layout is NULL");
        else
            System.out.println("Layout is not null");

        TableRow tbrow0 = new TableRow(this);
        TextView tv0 = new TextView(this);
        tv0.setText("Date");
        tv0.setTextColor(Color.WHITE);
        tbrow0.addView(tv0);
        TextView tv1 = new TextView(this);
        tv1.setText(" Amount ");
        tv1.setTextColor(Color.WHITE);
        tbrow0.addView(tv1);
        TextView tv2 = new TextView(this);
        tv2.setText(" Discount ");
        tv2.setTextColor(Color.WHITE);
        tbrow0.addView(tv2);

        for (int i = 0; i < _loanTerm; ++i) {
            TableRow tbrow = new TableRow(this);
            TextView t1v = new TextView(this);
            t1v.setText("" + i);
            t1v.setTextColor(Color.WHITE);
            t1v.setGravity(Gravity.CENTER);
            tbrow.addView(t1v);
            TextView t2v = new TextView(this);
            t2v.setText("Product " + i);
            t2v.setTextColor(Color.WHITE);
            t2v.setGravity(Gravity.CENTER);
            tbrow.addView(t2v);
            tableLayout.addView(tbrow);
        }
    }
}

public class MyTableFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.my_table, container, false);
    }
}

public class PagerAdapter extends FragmentStatePagerAdapter {
    private int _numOfTabs;

    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this._numOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                TabFragment1 tab1 = new TabFragment1();
                return tab1;
            case 1:
                TabFragment2 tab2 = new TabFragment2();
                return tab2;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return _numOfTabs;
    }

這是activity_main.xml

<RelativeLayout
    android:id="@+id/main_layout"
    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"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"/>

</RelativeLayout>

這是tab_fragment_1.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/AMOUNT"
    android:id="@+id/textView"
    android:layout_alignBottom="@+id/Amount"
    android:layout_toStartOf="@+id/calculateButton" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/Amount"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/RATE"
    android:id="@+id/textView2"
    android:layout_marginTop="32dp"
    android:layout_below="@+id/Amount"
    android:layout_alignEnd="@+id/textView" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/rate"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignStart="@+id/Amount" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/DISCOUNT"
    android:id="@+id/textView4"
    android:layout_centerVertical="true"
    android:layout_toStartOf="@+id/calculateButton" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:id="@+id/discount"
    android:editable="false"
    android:inputType="none"
    android:layout_alignBottom="@+id/textView4"
    android:layout_alignStart="@+id/rate" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/CALCULATE"
    android:id="@+id/calculateButton"
    android:clickable="true"
    android:enabled="true"
    android:onClick="onButtonClick"
    android:layout_above="@+id/payment"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="27dp" />

</RelativeLayout>

這是tab_fragment_2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab 2"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

這是我的my_table.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#3d455b"
        android:layout_alignParentLeft="true" >

        <HorizontalScrollView
            android:id="@+id/hscrll1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <RelativeLayout
                android:id="@+id/RelativeLayout1"
                android:layout_width="fill_parent"
                android:layout_gravity="center"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TableLayout
                    android:id="@+id/table_main"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true" >
                </TableLayout>
            </RelativeLayout>
        </HorizontalScrollView>
    </ScrollView>

</LinearLayout>

在我嘗試訪問時在我的 init() 中

TableLayout tableLayout = (TableLayout) findViewById(R.id.table_main);

它返回空

我錯過了什么?

謝謝

如果你想膨脹一個片段,你應該首先在活動主里面有一個框架布局,然后替換所選片段的框架布局。

公共類 MainActivity 擴展 AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //change content_frame for the id fiven to the frame layout inside activity_main
    getFragmentManager().beginTransaction().add(R.id.content_frame, new MyTableFragment()).commit();

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

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Loan Details"));
    tabLayout.addTab(tabLayout.newTab().setText("Amortization"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    this.init();
}

}

public class MyTableFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.my_table, container, false); } }

public class MyTableFragment extends Fragment {
 View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view =  inflater.inflate(R.layout.my_table, container, false);
    //in here you find the table using the view
    TabLayout tabLayout = (TabLayout)view.findViewById(R.id.tab_layout);

    return view;
}

}

您必須首先在您的活動中使用您的片段

執行以下操作:

首先在您的主要活動布局中定義容器以托管您的片段並為其分配 id,假設此 id 為“fragment_container”,因此在該行之后:

setContentView(R.layout.activity_main);

添加以下行:

getFragmentManager().beginTransaction().add(R.id.fragment_container, new MyTableFragment()).commit();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM