android - 如何将文本从 Activity(从 gridView 中选择的项目)发送到 fragment 并将文本发送到按钮

标签 android gridview adapter

Image

你好伙计。如你所见,我有 Activity 、游戏 fragment 、适配器

在我的 Activity 中是 gidView,对于这个 gridview,我创建了包含 8 个项目(按钮)的 ButtonAdapter

我想将 buttonsNamePostion 赋予 gameFragment。

在 ButtonAdapter 中,我得到了按钮名称。因此,当我在 Activity 中时,我有带有 Adapter 按钮的 GridView。我在 Activity 中尝试做类似的事情:

public String setText(){
return gridViewCurrency.getSelectedItemId().toString();
}

然后在GameFragmet中

private void setButtonCurrencyText(){
buttonCurrency.setText(((ActivityCurrency).getContext).setText());
}

但这没有用。

我为此花费了太多时间,我的大脑快要爆炸了。我该怎么做?

问题是。我想从 GridView 获取 ItemName 并且当我单击项目时,我的 fragment 被打开并且在我的 buttonCurrency 上是来自单击项目的文本。请帮助我

我不知道该怎么做。

这是 Activity

公共(public)类 CurrencySelectActivity 扩展 AppCompatActivity {

private final String TAG = this.getClass().getSimpleName();
private GridView gridViewCurrency;
private MainGameFragment mainGameFragment;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_currency_select);
    ButterKnife.bind(this);

    gridViewCurrency = (GridView) findViewById(R.id.gridview);

    configureGridViewCurrencySelect();
}

public void openGameFragment() {
    mainGameFragment = new MainGameFragment();
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.activity_currency_select, mainGameFragment, "fragment")
            .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
            .commit();
}

public void closerGameFragment() {
    getSupportFragmentManager()
            .beginTransaction()
            .hide(mainGameFragment)
            .commit();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}
private void configureGridViewCurrencySelect() {
    gridViewCurrency.setAdapter(new ButtonAdapter(this));
    gridViewCurrency.setNumColumns(4);

    gridViewCurrency.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(getApplicationContext(), position, Toast.LENGTH_SHORT).show();
        }
    });
}

这里是 ButtonAdapter

public class ButtonAdapter extends BaseAdapter {
private Context mContext;

public ButtonAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return buttonsName.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    Holder holder;
    if (convertView == null) {
        holder = new Holder();
        convertView = LayoutInflater.from(mContext).inflate(R.layout.row_button, null);
        holder.button = (Button) convertView.findViewById(R.id.button);
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((CurrencySelectActivity)mContext).openGameFragment();
            }
        });

        convertView.setTag(holder);

    } else {
        holder = (Holder) convertView.getTag();
    }

    holder.button.setText(buttonsName[position]);
    return convertView;
}

private class Holder {
    private Button button;

}

private String[] buttonsName = {"EUR/USD", "GBP/USD", "USD/CHF", "USD/JPY",
        "EUR/GBP", "EUR/JPN", "EUR/CHF", "USD/NOK",};

和gameFragment

public class MainGameFragment extends Fragment {

    @BindView(R.id.spinner_money)
    Spinner spinnerData;
    @BindView(R.id.text_profit_ill)
    TextView text_profit;
    @BindView(R.id.button_cash)
    Button btnCashCurrency;
    @BindView(R.id.restart_game)
    Button restartGame;
    @BindView(R.id.butonCurrency)
    Button buttonCurrency;

    public MainGameFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_game, container, false);


        CandleStickChart mChart = (CandleStickChart) view.findViewById(R.id.chart);

        mChart.getDescription().setEnabled(false);

        mChart.setMaxVisibleValueCount(40);

        mChart.animateX(3000);


        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setDrawGridLines(false);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setDrawGridLines(false);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setTextColor(Color.WHITE);

//        chart.getAxisLeft().setTextColor(...); // left y-axis
//        chart.getXAxis().setTextColor(...);
//        chart.getLegend().setTextColor(...);

        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);

        ArrayList<CandleEntry> yVals1 = new ArrayList<>();
        int prog = ((int) (Math.random() * 80));

        for (int i = 0; i < prog; i++) {

            float val = (float) (Math.random() * 2);
            float high = (float) (Math.random() * 1) + 2f;
            float low = (float) (Math.random() * 1) + 2f;

            float open = (float) (Math.random() * 2) + 1f;
            float close = (float) (Math.random() * 2) + 1f;

            boolean even = i % 2 == 0;

            yVals1.add(new CandleEntry(i, val + high, val - low, even ? val + open : val - open,
                    even ? val - close : val + close));

            String date = String.valueOf(android.text.format.DateFormat.format("yyyy-MM-dd", new java.util.Date()));

            CandleDataSet set1 = new CandleDataSet(yVals1, date);

            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(Color.rgb(80, 80, 80));
            set1.setShadowColor(Color.DKGRAY);
            set1.setShadowWidth(0.7f);
            set1.setDecreasingColor(Color.RED);
            set1.setDecreasingPaintStyle(Paint.Style.FILL);
            set1.setIncreasingColor(Color.GREEN);
            set1.setIncreasingPaintStyle(Paint.Style.FILL);
            set1.setNeutralColor(Color.BLUE);
            set1.setHighlightLineWidth(1f);
            set1.setBarSpace(0.2f);

            CandleData data = new CandleData(set1);

            mChart.setData(data);
            mChart.invalidate();
            mChart.getLegend().setEnabled(false);
            ButterKnife.bind(this, view);
            configureSpinnerDataAndLogic();

        }
        return view;
    }

    @OnClick({R.id.btn_buy, R.id.btn_sell})
    public void onGlobalSearchClicked() {
        int cash = Integer.valueOf(btnCashCurrency.getText().toString());
        if (cash < 0) {
            restartGame.setVisibility(View.VISIBLE);
            Toast.makeText(getContext(), "Your cash is on -, u cant play. Please restart game.", Toast.LENGTH_SHORT).show();
        } else {
            FragmentTransaction ft = getChildFragmentManager().beginTransaction();
            ft.addToBackStack(null);
            int min = 0;
            int max = 2;
            Random r = new Random();
            int i1 = r.nextInt(max - min + 1) + min;
            String text = spinnerData.getSelectedItem().toString();
            int temp = Integer.parseInt(text);
            int temp2 = temp * 2;
            if (i1 == 0 || i1 == 1) {
                DialogFragment newFragment = LostDialogFragment.newInstance(1);
                String DIALOG_LOST = "LostDialogFragment";
                newFragment.show(ft, DIALOG_LOST);
                cash -= temp2;
                btnCashCurrency.setText(cash + "");
            } else {
                DialogFragment newFragment = WinDialogFragment.newInstance(1);
                String DIALOG_WIN = "WinDialogFragment";
                newFragment.show(ft, DIALOG_WIN);
                cash += temp2;
                btnCashCurrency.setText(cash + "");
            }
        }
    }

    @OnClick(R.id.restart_game)
    public void restartGame() {
        ((CurrencySelectActivity) getContext()).onBackPressed();
    }

//    @OnClick(R.id.button_cash)
//    public void openHistoryGames() {
//        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
//        ft.addToBackStack(null);
//        DialogFragment newFragment = GameHistoryFragment.newInstance(1);
//        String DIALOG_HISTORY = "HistoryDialogFragment";
//        newFragment.show(ft, DIALOG_HISTORY);
//    }

    private void configureSpinnerDataAndLogic() {
        String[] arraySpinner = new String[]{
                "50", "100", "150", "200", "250", "300", "500"
        };
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_spinner_item, arraySpinner);
        spinnerData.setAdapter(adapter);
        spinnerData.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String text = spinnerData.getSelectedItem().toString();
                int temp = Integer.parseInt(text);
                text_profit.setText((temp * 2) + " $ " + "100%");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }
}

最佳答案

像这样将位置传递给 Activity 的 openGameFragment 函数:

holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((CurrencySelectActivity)mContext).openGameFragment(position+1);
            }
        });

在 openGameFragment 函数中将 bundle 添加到 fragment 对象:

public void openGameFragment(int position) {
    mainGameFragment = new MainGameFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("button_position", position);
    mainGameFragment.setArguments(bundle);
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.activity_currency_select, mainGameFragment, "fragment")
            .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
            .commit();
}

在 MainGameFragment 的 OnCreate 中,从包中检索这些值。

private int buttonPosition;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            buttonPosition = getArguments().getInt("button_position", 0);
        }
    }

您可以以相同的方式将文本传递给 bundle,并相应地使用这些值。

关于android - 如何将文本从 Activity(从 gridView 中选择的项目)发送到 fragment 并将文本发送到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42225007/

相关文章:

android - 在 Android 中的特定日期和时间运行 Activity

android - 模拟器 : ERROR: A snapshot operation for 'Nexus_4_API_27' is pending and timeout has expired. 退出

asp.net - 扫描每列中的每个 gridview 行,如果所有行都为空,则隐藏该列

c# - ASP.Net gridview如何实现多colspan和多header row?

java - Android Studio 与 Java : ArrayAdapter not working correctly

安卓 : Implementation of two way Endless Viewpager

android - 用于GridView的Android文本和图像适配器的 fragment

android - 如何将自定义布局添加到 Arrayadapter?

android - 从 Spinner 获取键和值的最佳方式

c# - 无法将 System.Web.UI.WebControls.Label 类型的对象转换为类型 System.IConvertible