Получите доступ к string_array из действия и отправьте выбранный элемент в другое действие в android - PullRequest
1 голос
/ 19 февраля 2020

Привет, друзья! Сегодня мой вопрос о string_array. В своей деятельности я создал две кнопки. Теперь (строки. xml) я создал имя массива строк с двумя элементами и вставил некоторый текст, как показано ниже. На каждой кнопке нажмите, я хотел бы получить доступ к каждому элементу в отдельности. Например, на кнопке 1 нажмите показать мне первый элемент и на кнопке 2 нажмите, дайте мне 2-й элемент на. Можете ли вы дать мне код для нажатия кнопки, так как у меня мало идей о том, как получить доступ item.I создал текстовое представление для отображения моего элемента с каждым кодом click.my до сих пор работает нормально, но мне нужна помощь с дополнительным кодом, который я должен добавить. Пожалуйста, помогите мне.

// Button activity page
android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="60dp"
        android:layout_marginRight="50dp"
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:text="@string/OKILA"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="160dp"
        android:layout_marginRight="50dp"
        android:text="1"
        android:textSize="18sp"
        android:textStyle="bold" />

</RelativeLayout>
//strings.xml
    <string-array name="chapters">
        <item>this is tes1</item>
        <item>this is test2</item>
    </string-array>
//main
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class Lipok extends AppCompatActivity implements View.OnClickListener {
    Toolbar mActionBarToolbar;
    Button btnOne;
    Button btnTwo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipok);
        mActionBarToolbar=(Toolbar)findViewById(R.id.CHAPTERS);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setTitle("CHAPTERS");
    String[] chapters=getResources().getStringArray(R.array.chapters);

        btnOne = findViewById(R.id.btn1);
        btnTwo = findViewById(R.id.button1);        

        btnOne.setOnClickListener(this);
        btnTwo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String text="";
        switch(v.getId()){
            case R.id.btn1 : {
                text = getResources().getStringArray(R.array.chapters)[0];
                break;
            }
            case R.id.button1 : {
                text = getResources().getStringArray(R.array.chapters)[1];
                break;
            }
        }


        Intent intent = new Intent(Lipok.this,lipokchapters.class);
        intent.putExtra("DATA", text);
        startActivity(intent);
    }
}

//textview activity page
package com.Aolai.temeshilai;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class lipokchapters extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipokchapters);
        textView=findViewById(R.id.textv);
        String text= getIntent().getStringExtra("Data");
        textView.setText(text);

    }
}

Ответы [ 2 ]

2 голосов
/ 19 февраля 2020

Попробуйте:

xml файл

android:layout_height="match_parent">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="60dp"
        android:layout_marginRight="50dp"
        android:id="@+id/OKILA"
        android:layout_width="wrap_content"
        android:text="@string/OKILA"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="160dp"
        android:layout_marginRight="50dp"
        android:text="1"
        android:textSize="18sp"
        android:textStyle="bold" />

</RelativeLayout>

строк. xml

    <string-array name="chapters">
        <item>this is tes1</item>
        <item>this is test2</item>
    </string-array>

Основной класс

public class Lipok extends AppCompatActivity implements View.OnClickListener {
    Toolbar mActionBarToolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipok);
        mActionBarToolbar=(Toolbar)findViewById(R.id.CHAPTERS);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setTitle("CHAPTERS");

    }

    @Override
    public void onClick(View v) {
         String text="";
         switch(v.getId()){
              case R.id.OKILA : {
                   text = getResources().getStringArray(R.array.testArray)[0];
                   break;
              }
              case R.id.button1 : {
                   text = getResources().getStringArray(R.array.testArray)[1];
                   break;
              }
         }
         Toast.makeText(this, text, Toast.LENGTH_LONG).show();

             Intent intent = new Intent(this, YOUR_ACTIVITY_NAME.class);
             intent.putExtra("DATA", text);
             startActivity(intent);

         // Or else you can do whatever you want to do here with that text
    }
}

Тогда в вашей другой деятельности

String data = getIntent().getStringExtra("DATA");
YOUR_TEXTVIEW_NAME.setText(data);
0 голосов
/ 19 февраля 2020

Это основы Android, поэтому, прежде чем ответить, я предлагаю вам go через базовые c учебники перед публикацией в Stackoberflow.

Теперь,

Вот как вы можете получить доступ к предметам из вашего string_array.

String[] chapters= getResources().getStringArray(R.array.chapters);

Теперь вот псевдокод, который может вам помочь.

btn1.setOnClickListener(

your_text_view.setText(chapters[0])

)
//Here 0 means your first item, likewise you can access items by their index in 
 array
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...