如何从MainActivity更新CustomListEntry的TextView?

时间:2018-02-23 05:09:36

标签: nullpointerexception textview

我有一个带有listView(id:listView1)的MainActivity,它有一个适用于listView1行的custom_list_entry.xml(一个TextView)的适配器。当行少于填充视图的行时(在我的情况下为5个条目),我想填充listView1。试图创建另一个类CustomListEntry,以便我可以获取TextView引用TextView tV = findViewbyId(R.id.customListTV),因为我无法从MainActivity获取它,这是setContentView到R.layout.activity_main。然后在MainActivity类中获取CustomListEntry customListEntry = new CustomListEntry()并将customListEntry.tV.setMinHeight调用到先前计算的屏幕尺寸高度/ listItemCount,这将有希望给出屏幕高度除以有多少条目并为每个条目指定高度。问题是我在运行MainActivity时遇到空指针异常。请帮忙!

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sjdav.text_game">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".CustomListEntry"></activity>
    </application>

</manifest>

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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.sjdav.text_game.MainActivity"
    android:id="@+id/background"
    android:weightSum="100"
    android:baselineAligned="false">

    <RelativeLayout
        android:id="@+id/pane_1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="25">

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:background="#3F45FA">

        </ListView>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/pane_2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="25">

        <ImageView
            android:id="@+id/iV1"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:contentDescription="@string/cont_Desc"
            android:src="@drawable/pokemon_1"/>

        <ListView
            android:id="@+id/listView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:background="#FFFFFF"
            android:layout_below="@id/iV1">

        </ListView>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/pane_3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="25">

        <ImageView
            android:id="@+id/iV2"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:contentDescription="@string/cont_Desc"
            android:src="@drawable/pokemon_3"/>

        <ListView
            android:id="@+id/listView3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:background="#FFFFFF"
            android:layout_below="@id/iV2">

        </ListView>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/pane_4"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="25">

    </RelativeLayout>

</LinearLayout>

custom_list_entry.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.sjdav.text_game.CustomListEntry"
    android:id="@+id/customListTV"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="20sp"
    android:textColor="@color/colorAccent"
    android:gravity="center_vertical"
    android:textAlignment="center"
    android:padding="8dp">

</TextView>

MainActivity.java:

package com.example.sjdav.text_game;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    public CustomListEntry customListEntry = new CustomListEntry();

    public float listItemHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_main);

        Log.i(TAG, "onCreate: MA >> Started..");

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        float density = metrics.density;
        float width = metrics.widthPixels / density;
        float height = metrics.heightPixels / density;

        Log.i(TAG, "onCreate: MA >> width: " + width);
        Log.i(TAG, "onCreate: MA >> hehight: " + height);

        ListView listView1 = findViewById(R.id.listView1);

        final ArrayList<String> menu = new ArrayList<>();
        menu.add(getString(R.string.start));
        menu.add(getString(R.string.settings));
        menu.add(getString(R.string.about));
        menu.add(getString(R.string.images));
        menu.add(getString(R.string.credits));

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.custom_list_entry, menu);

        listView1.setAdapter(adapter);

        int listItemsCount = listView1.getAdapter().getCount();
        Log.i(TAG, "onCreate: MA >> listVew1 item count: " + listItemsCount);

        float custom_dimen = getResources().getDimension(R.dimen.custom_list_entry_height) / density;
        Log.i(TAG, "onCreate: MA >> list dimen: " + custom_dimen);

        listItemHeight = height / listItemsCount;
        Log.i(TAG, "onCreate: MA >> listView1 listItemHeight: " + listItemHeight);

        customListEntry.tV.setMinHeight((int)listItemHeight);

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "onItemClick: MA >> menu: " + menu.get(position));
                // When click on menu item, show/hide other views by setting visibility and focusable and clickable
            }
        });
    }
}

CustomListEntry.java:

package com.example.sjdav.text_game;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class CustomListEntry extends AppCompatActivity {

    public TextView tV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        setContentView(R.layout.custom_list_entry);

        tV = findViewById(R.id.customListTV);
    }
}

1 个答案:

答案 0 :(得分:0)

你做错了。创建自定义适配器并在自定义适配器上为视图充气。

这会对你有所帮助

public class ListCustomAdapter extends ArrayAdapter<String> {
    private TextView customListTV;

    public ListCustomAdapter(Context context, int resource, ArrayList<String> objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try{
                LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.custom_list_entry,null,false);
                customListTV = (TextView) convertView.findViewById(R.id.customListTV);

                String data = getItem(position);                    
                customListTV.setText(data);
        }catch (Exception e){
            e.printStackTrace();
        }

        return convertView;
    }
}

在您的主活动中创建适配器类的对象

ListCustomAdapter adapter = new ListCustomAdapter(this,R.layout.activity_main,menu);
setListAdapter(adapter);