简体   繁体   English

尝试通过单击按钮更改textView中的文本大小时应用程序崩溃

[英]App Crash When Trying to Change textsize in textView by clicking on button

In One Of my Activity I have a Menu Option With Text Option When user Click That it redirect to Another Layout where I Kept Two Buttons one is Plus Button and Another One is Minus Button 在我的一个活动中,我有一个带文本选项的菜单选项当用户点击它重定向到另一个布局我保留两个按钮一个是加号按钮而另一个是减号按钮

When user Click that Button I want to Change The TextView Text Size of the BackStack Activity 当用户单击该按钮时,我想更改BackStack活动的TextView文本大小

Here is My Code Below When i click that MenuOPtion the App was Crash and it Report NullPointerException in Logcat 这是下面的我的代码当我点击那个MenuOPtion时,应用程序崩溃,它在Logcat中报告NullPointerException

My Detail Activity 我的细节活动

@Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_activity);

 detailtext= (TextView) findViewById(R.id.detail);
 dbHelper = new SqlLiteDbHelper(this);
        try {
            dbHelper.openDataBase();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        sqLiteDatabase = dbHelper.getReadableDatabase();
        cursor=dbHelper.getdetails(sqLiteDatabase, selectedData);

        if(cursor.moveToFirst())
        {

            detailtext.setText(cursor.getString(0));
        }

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
 int id = item.getItemId();
 if (id==R.id.text_option)
        {
           Intent intent= new Intent(this,CustomSetting.class);
            startActivity(intent);

        }
return super.onOptionsItemSelected(item);
    }

Detail_menu.xml Detail_menu.xml

 <item android:id="@+id/text_option"
        android:orderInCategory="100"
        android:showAsAction="ifRoom"
        android:title="Text Option"
         />

CustomSetting.java CustomSetting.java

public class CustomSetting extends AppCompatActivity {

    DetailActivity detailActivity;
    ImageButton plus,minus,close;
    int txtSize = 14;
    TextView detail=detailActivity.detailtext;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_setting);
        plus= (ImageButton) findViewById(R.id.plus);
        minus= (ImageButton) findViewById(R.id.minus);
        close= (ImageButton) findViewById(R.id.close);

plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (detail.getTextSize() == 14 ||detail.getTextSize() == 15 || detail.getTextSize() == 16 || detail.getTextSize() == 17){
                    txtSize++;
                    detail.setTextSize(txtSize);
                } else if (detail.getTextSize() == 18) {
                    txtSize+= 0;
                    detail.setTextSize(txtSize);
                } else{
                    txtSize+= 0;
                    detail.setTextSize(txtSize);
                }

            }
        });
        minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (detail.getTextSize() == 15||detail.getTextSize() ==16||detail.getTextSize() ==17|detail.getTextSize() ==18){
                    txtSize--;
                    detail.setTextSize(txtSize);
                } else {
                    txtSize += 0;
                    detail.setTextSize(txtSize);
                }

            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent(CustomSetting.this,DetailActivity.class);
                startActivity(intent);
            }
        });

    }

custom_setting.xml custom_setting.xml

<ImageButton
    android:layout_width="50dp"
    android:layout_height="40dp"
    android:background="@drawable/close"
    android:layout_above="@+id/textView"
    android:layout_toRightOf="@+id/minus"
    android:layout_toEndOf="@+id/minus"
    android:id="@+id/close"
    />
    <ImageButton
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:background="@drawable/plusign"
        android:layout_marginTop="110dp"
        android:id="@+id/plus"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView" />
    <ImageButton
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:background="@drawable/minusign"
        android:id="@+id/minus"
        android:layout_alignTop="@+id/plus"
        android:layout_alignRight="@+id/textView"
        android:layout_alignEnd="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Change Text Size"
        android:id="@+id/textView"
        android:layout_above="@+id/minus"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        />

Logcat: logcat的:

   Process: com.example.aa.sidd, PID: 23413
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aa.sidd/com.example.aa.sidd.CustomSetting}: android.view.InflateException: Binary XML file line #17: Error inflating class <unknown>
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
            at android.app.ActivityThread.access$900(ActivityThread.java:179)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5641)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class <unknown>
            at android.view.LayoutInflater.createView(LayoutInflater.java:626)

Display the new layout in the form of a DialogFragment. 以DialogFragment的形式显示新布局。 The idea is to show the increase/Decrease option in the form of a DialogFragment popup. 我们的想法是以DialogFragment弹出窗口的形式显示增加/减少选项。 you can increase/decrease size from the popup. 你可以从弹出窗口增加/减少大小。 Once the popup dismisses the selected size is set to the TextView in your Activity. 弹出窗口解除后,所选大小将设置为Activity中的TextView。

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity {

public static int updatedSize;
TextView greetingText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    greetingText = (TextView)findViewById(R.id.hello_world_text);
}

@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) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        mycustomLayout();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void mycustomLayout(){
    FragmentManager manager = getFragmentManager();
    PopUp popUp = new PopUp(new FragmentDismissHandler());
    popUp.show(manager,"POPUP");

}

public void refreshText(){
    if( updatedSize>0)
    greetingText.setTextSize(updatedSize);
}

private class FragmentDismissHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        refreshText();
    }
}

}

PopUp.java (custom layout as DialogFragment) PopUp.java(自定义布局为DialogFragment)

public class PopUp extends DialogFragment implements View.OnClickListener{

ImageButton increase,decrease,set;
TextView sizeOfText;
static int size;
Handler handler;


public PopUp(Handler handler) {
    this.handler = handler;
}
public PopUp(){

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    getDialog().setTitle("change text size");
    View view = inflater.inflate(R.layout.my_custom_layout, container, false);

    increase = (ImageButton)view.findViewById(R.id.inc);
    increase.setOnClickListener(this);

    decrease = (ImageButton)view.findViewById(R.id.dec);
    decrease.setOnClickListener(this);

    sizeOfText = (TextView)view.findViewById(R.id.size_text);
    sizeOfText.setText("text");

    set = (ImageButton)view.findViewById(R.id.ok);
    set.setOnClickListener(this);

    size = (int) sizeOfText.getTextSize();

    return view;
}


@Override
public void onClick(View view) {
    int id= view.getId();

    if(id==R.id.inc){
        size = size +1;
        sizeOfText.setText("text");
        sizeOfText.setTextSize(size);
    }
    if(id== R.id.dec){
        size = size - 1;
        sizeOfText.setText("text");
        sizeOfText.setTextSize(size);
    }
    if(id== R.id.ok){
        dismiss();
    }
}

@Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    MainActivity.updatedSize = size;
    handler.sendEmptyMessage(0);
}

}
if (id==R.id.text_option) 

but the id of the menu is display right as explained below 但菜单的ID显示正确,如下所述

item android:id="@+id/display"

So I think it should be 所以我认为应该如此

if (id==R.id.display) //like this

Though this question already have accepted answer, but it is bad programming practice to have static control references. 虽然这个问题已经接受了答案,但是有静态控制参考是不好的编程实践。

Instead you have intents for data passing, so when opening CustomSetting activity you should pass textview textsize as intent extra something like this:- 相反,你有意图进行数据传递,所以当打开CustomSetting活动时,你应该将textview textsize作为intent更多地传递出来: -

Intent intent= new Intent(this,CustomSetting.class);
intent.putExtra("textview_size",detailtext.getTextSize());
startActivity(intent);

Inside CustomSetting onCreate you can do 在CustomSetting onCreate里面你可以做到

if (getIntent().hasExtra("textview_size"){
  font_size = getIntent().getFloatExtra("textview_size",<default_size_your_want>);
}

While clicking on + or - button you can use 点击+或 - 按钮即可使用

font_size += 1 

or 要么

fontsize -= 1

When clicked on close button you can do 单击关闭按钮即可

Intent intent= new Intent(CustomSetting.this,DetailActivity.class);
intent.putExtra("textview_size",fontsize);
startActivity(intent);

and in your DetailActivity oncreate you can do 在你的DetailActivity oncreate中你可以做到

if (getIntent().hasExtra("textview_size"){
  font_size = getIntent().getFloatExtra("textview_size",<default_size_your_want>);
  detailtext.setTextSize(font_size);
}

Three things, 三件事,
From your original question: 从你原来的问题:
you would be getting a null pointer exception from attempting to access an uninitialised object. 您将尝试访问未初始化的对象获取空指针异常。 In this case an activity. 在这种情况下是一项活动。

DetailActivity detailActivity;
ImageButton plus,minus,close;
/.../
TextView detail=detailActivity.detailtext;

And what you are trying to attempt is not possible in the way you are trying to do this. 而你尝试尝试的方式是不可能的。 Please see this link from a well known android expert. 请从知名的android专家那里看到这个链接。
https://stackoverflow.com/a/6693367/3956566 which answers a similar question here Get reference of one Activity from another in android https://stackoverflow.com/a/6693367/3956566这里回答类似的问题在android中获取另一个Activity的参考

Another, possible, problem could be your resources. 另一个可能的问题可能是您的资源。 You are loading multiple image buttons, ensure that your images are not too big in size (bytes). 您正在加载多个图像按钮,确保您的图像不是太大(字节)。

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aa.sidd/com.example.aa.sidd.CustomSetting}: android.view.InflateException: Binary XML file line #17: Error inflating class java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.aa.sidd / com.example.aa.sidd.CustomSetting}:android.view.InflateException:二进制XML文件行#17:错误膨胀类

See this question: 看到这个问题:
android.view.InflateException: Binary XML file line #12: Error inflating class <unknown> android.view.InflateException:二进制XML文件行#12:错误膨胀类<unknown>

Thirdly, as I mentioned in the comments, I don't think declaring members as static as a work around is a good idea, see here Avoiding memory leaks Static members, methods and classes need to be used sparingly and with thought when planning any application. 第三,正如我在评论中提到的,我不认为将成员声明为静态作为解决方案是一个好主意,请参阅此处避免内存泄漏静态成员,方法和类需要在规划任何应用程序时谨慎使用。 In any language. 用任何语言。 Well that's my opinion. 那是我的意见。

I assume you have some line in DetailActivity like 我假设你在DetailActivity中有一些像

Textview detailtext;

change it to 改为

static Textview detailtext;

then get rid of your 然后摆脱你的

DetailActivity detailActivity;

and change the line 并改变线

TextView detail=detailActivity.detailtext;

to

TextView detail=DetailActivity.detailtext;

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM