Можно ли добавить метод On Click Button во фрагмент? - PullRequest
0 голосов
/ 17 февраля 2020

Я добавил кнопку в файл xml. Теперь я хочу открыть ее во фрагменте. Я пытаюсь показать опцию общего доступа при нажатии кнопки, но не работает FindView, и ничего не происходит при нажатии кнопки после RUN. Может быть, это код для обмена .. Я в замешательстве .. Пожалуйста, помогите

Я сделал все возможное .. Любая помощь будет оценена .. Спасибо всем экспертам

(XML Файлы)

Activity_main:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation"
        />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemIconTint="@color/selector_item_gray_color"
        app:itemTextColor="@color/selector_item_gray_color"
        android:background="#302E2D"
        app:menu="@menu/bottom_navigation_android" />



</RelativeLayout>  

frag_more:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:layout_centerInParent="true"
    android:background="#fff"
    android:gravity="center_horizontal">

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center_horizontal">

        <androidx.appcompat.widget.SwitchCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Night Mode"
            android:textColor="@color/textcolour"></androidx.appcompat.widget.SwitchCompat>

        <Button
            android:id="@+id/btn_share"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_marginTop="85dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Share"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option2"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_share"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Recommend to friends"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />


        <Button
            android:id="@+id/btn_option3"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option2"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Get Free Islamic Apps"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option4"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option3"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Rate and Feedback"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option5"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option4"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Help"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/textview6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="Example Text"
            android:textSize="12sp"
            android:textColor="#000000"/>

    </LinearLayout>


</RelativeLayout>

(Java Files)

Main_Activity:

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

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

        BottomNavigationView bottomnav = findViewById(R.id.bottom_navigation);
        bottomnav.setOnNavigationItemSelectedListener(navListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new Home_Fragment()).commit();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem MenuItem) {
                    Fragment selectedFragment = null;

                    switch (MenuItem.getItemId()) {
                        case R.id.nav_home:
                            selectedFragment = new Home_Fragment();
                            break;
                        case R.id.nav_settings:
                            selectedFragment = new More_Fragment();
                            break;
                    }

                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            selectedFragment).commit();

                    return true;
                }
            };
}

Fragment_More:

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class More_Fragment extends Fragment {

    Button btn;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_more, container,false);}





}

Даже пробовал этот код в Fragment_More Но не удалось

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class More_Fragment extends Fragment {

    private String a = "";
    private String b = "";

    private LinearLayout linear1;
    private Button btn_share;
    private TextView textview6;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_more, container,false);}

    private void initialize(Bundle _savedInstanceState) {

        linear1 = (LinearLayout) getActivity().findViewById(R.id.linear1);
        btn_share = (Button) getActivity().findViewById(R.id.btn_share);
        textview6 = (TextView) getActivity().findViewById(R.id.textview6);

        btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View _view) {
                a = textview6.getText().toString();
                b = textview6.getText().toString();
                Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
            }
        });
    }
    private void initializeLogic() { textview6.setVisibility(View.GONE);
    }

}

Ответы [ 2 ]

0 голосов
/ 22 февраля 2020

Вот как это делается ... Спасибо миллиону экспертов.

Fragment_More. java

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class More_Fragment extends Fragment{

    private String a = "";
    private String b = "";

    private LinearLayout linear1;
    private Button btn_sharethis;
    private TextView text;


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_more, container,false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        btn_sharethis = (Button)view.findViewById(R.id.btn_shareme);
        text = (TextView)view.findViewById(R.id.textview61);

        btn_sharethis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                a = text.getText().toString();
                b = text.getText().toString();
                Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
            }
        });
    }
}
0 голосов
/ 17 февраля 2020

Чтобы сослаться на вашу кнопку внутри фрагмента, вы хотите сделать это в onCreateView:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     View rootView = inflater.inflate(R.layout.fragment_more, container,false);
     btn_share = (Button) rootView.findViewById(R.id.btn_share);
     btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View _view) {
                a = textview6.getText().toString();
                b = textview6.getText().toString();
                Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
            }
        });
     return rootView;
}
...