如何在Android的按钮的OnClickListener中放置if语句

时间:2017-04-24 01:48:59

标签: java android

我正在处理我的主要项目,我希望我的按钮根据获得的字符串数组值打开不同的意图。我在按钮的OnClickListener中使用了if和else if语句,但它不再单击了。请帮帮我。

这是我的XML文件:

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    app:cardCornerRadius="3dp"
    app:cardElevation="2dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/spacing_large">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/spacing_middle"
        android:text="Syllabus"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

    <Button
        android:id="@+id/buttonpdf"
        style="@style/Widget.AppCompat.Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="Open Book" />

</LinearLayout> 

这是同一活动的Java文件:

public class ActivityBookDetails extends AppCompatActivity {

    public static final String EXTRA_OBJCT = "com.app.sample.recipe.OBJ";

    private Book book;
    private FloatingActionButton fab;
    private View parent_view;

    Button button;
    String[] obj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_book_details);
        parent_view = findViewById(android.R.id.content);
        button = (Button)findViewById(R.id.buttonpdf);


        book = (Book) getIntent().getSerializableExtra(EXTRA_OBJCT);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fabToggle();
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(book.getName());

        ((ImageView) findViewById(R.id.image)).setImageResource(book.getPhoto());

        LinearLayout subjects = (LinearLayout) findViewById(R.id.subjects);


        final String[] title_subjects = getResources().getStringArray(R.array.Subjects);
        addIngredientsList(subjects, title_subjects);
        obj = title_subjects;

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("Soft Computing".equals(obj)) {
                    Intent intent = new Intent(ActivityBookDetails.this, pdfviewactivity.class);

                    startActivity(intent);
                }
                else if ("Web Engineering".equals(obj)) {
                    Intent intent = new Intent(ActivityBookDetails.this, pdfweben.class);

                    startActivity(intent);
                }
                else if ("Network Management".equals(obj)) {
                    Intent intent = new Intent(ActivityBookDetails.this, pdfnetwork.class);

                    startActivity(intent);
                }
                else if ("Wireless Network".equals(obj)) {
                    Intent intent = new Intent(ActivityBookDetails.this, pdfwireless.class);

                    startActivity(intent);
                }
            }
        });

我希望我的if else条件能够在字符串数组的基础上工作。

这是给定意图之一的示例Java文件:

public class pdfwireless extends AppCompatActivity {
    PDFView pdfView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdfwireless);
        pdfView = (PDFView)findViewById(R.id.pdfView);
        pdfView.fromAsset("wirelessnetwork.pdf").load();
    }
}

2 个答案:

答案 0 :(得分:1)

您可能不应该尝试在86.5%中添加条件,而最简单的方法是将条件逻辑移动到另一个方法中。例如。

OnClickListener

正如cricket_007已经建议的那样,有比使用if / else if语句更好的方法。如果您打算添加更多选项,可以考虑使用枚举或地图。

@Override
public void onClick(View view){
    goToNextView();
}

private void goToNextView(){
    if (title_subjects[0] == "Soft Computing") {
        Intent intent = new Intent(ActivityBookDetails.this, pdfviewactivity.class);
        startActivity(intent);
    }
    // else if {}
    // else {}
}

最简单的改变是使用HashMap,尽管这样做的缺点是每次添加新主题时都需要更改public enum Subjects { SOFT_COMPUTING("Soft Computing", pdfviewactivity.class), WEB_ENGINEERING("Web Engineering", pdfweben.class), NETWORK_MANAGEMENT("Wireless Network", pdfnetwork.class), WIRELESS_NETWORK("Network Management", pdfwireless.class); private String name; private Class clazz; Subjects(String name, Class clazz){ this.name = name; this.clazz = clazz; } public static Class getClass(String title_subject) { for(Subjects subject: Subjects.values()) { if (subject.name.equals(title_subject)) { return subject.clazz; } } return null; } } private void goToNextView() { //Alternative to conditionals using Enum Class theClassToGoTo = Subjects.getClass(title_subjects[0]); Intent intent = new Intent(ActivityBookDetails.this, theClassToGoTo); startActivity(intent); //Alternative to conditionals using HashMap Map<String, Class> subject_map = new HashMap<>(); subject_map.put("Soft Computing", pdfviewactivity.class); subject_map.put("Web Engineering", pdfweben.class); subject_map.put("Wireless Network", pdfnetwork.class); subject_map.put("Network Management", pdfwireless.class); Class theClassToGoTo2 = subject_map.get(title_subjects[0]); Intent intent2 = new Intent(ActivityBookDetails.this, theClassToGoTo2); startActivity(intent); } 方法。 Enum涉及更多代码,但更容易清理,因为一切只有一个改变的目的。

还有其他方法可以做到这一点,上面只是两个简单的建议,不涉及更改现有代码太多。

答案 1 :(得分:0)

让我们看看......

final String[] title_subjects = getResources().getStringArray(R.array.Subjects);
obj = title_subjects;

和...

if ("Soft Computing".equals(obj)) {

(注意:obj变量在这里毫无意义)

好吧,String永远不会等于String[],所以问题就出现了。

你需要

1)从该数组中获取一个单独的字符串进行比较,

2)获取R.string资源,而不是R.array

3)也许使用boolean contains(String[] strings, String findMe)方法的一些实现。但是,我不知道这是否适用于您所显示的逻辑

4)使用其他更有意义的条件......就像你有book.getSubject()

选项1,例如......

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String s0 = title_subjects[0]; // Get just the first string

        Class clz = null;

        if ("Soft Computing".equals(s0)) {
            clz =  pdfviewactivity.class;
        } else if ("Web Engineering".equals(s0)) {
            clz = pdfweben.class;
        else if ("Network Management".equals(s0)) {
            clz = pdfnetwork.class;
        } else if ("Wireless Network".equals(s0)) {
            clz = pdfwireless.class;
        }

        if (clz != null) {
            Intent intent = new Intent(ActivityBookDetails.this, clz);
            startActivity(intent);
        }
    }
});

使用Map<String, Class>看起来比if-else语句更清晰