How to add more than one same custom view to a grid layout in android from Java code - android-layout

I am learning custom views in android.
I made one custom view, with a rectangle and a text. The code of the custom view is:
public class TileGenerator extends View {
// rectangle parameters
private Rect rect = new Rect();
private Paint rectPaint = new Paint();
private Integer rectEndX;
private Integer rectEndY;
private Integer rectStartX;
private Integer rectStartY;
private Integer rectFillColor;
private Float rectTextStartX;
private Float rectTextStartY;
//rectangle text
private String rectText;
private Paint rectTextPaint = new Paint();
public TileGenerator(Context context) {
super(context);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void setTileTitleText(String rectText) {
this.rectText = rectText;
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
rectEndX = getrectEndX();
rectEndY = getrectEndY();
rectStartX = getRectStartX();
rectStartY = getRectStartY();
rectTextStartX = rectEndX/4f + rectStartX;
rectTextStartY = 3.5f * rectEndY/4f + rectStartY;
rectTextPaint.setTextSize(rectEndY/8);
rectTextPaint.setColor(Color.BLACK);
rect.set(rectStartX,rectStartY,rectEndX,rectEndY);
rectPaint.setColor(getRectFillColor());
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(rect, rectPaint);
canvas.drawText(rectText,rectTextStartX,rectTextStartY,rectTextPaint );
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
public Integer getrectEndX() {
return rectEndX;
}
public void setrectEndX(Integer rectEndX) {
this.rectEndX = rectEndX;
}
public Integer getrectEndY() {
return rectEndY;
}
public void setrectEndY(Integer rectEndY) {
this.rectEndY = rectEndY;
}
public Integer getRectStartX() {
return rectStartX;
}
public void setRectStartX(Integer rectStartX) {
this.rectStartX = rectStartX;
}
public Integer getRectStartY() {
return rectStartY;
}
public void setRectStartY(Integer rectStartY) {
this.rectStartY = rectStartY;
}
public Integer getRectFillColor() {
return rectFillColor;
}
public void setRectFillColor(Integer rectFillColor) {
this.rectFillColor = rectFillColor;
}
public String getRectText() {
return rectText;
}
}
After that I created an blank activity. I am doing all with JAVA code. No XML. Then I try to add above custom view to a gridview layout. I want to add two custom views with different text in a horizontal gridview. So far my code is as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GridLayout gridLayout = new GridLayout(this);
// first custom view
CustomRectWithText customRectWithText = new CustomRectWithText(this);
customRectWithText.setRectEndX(200);
customRectWithText.setRectEndY(200);
customRectWithText.setRectStartX(2);
customRectWithText.setRectStartY(2);
customRectWithText.setImage(image);
customRectWithText.setRectText("Text");
customRectWithText.setRectFillColor(Color.BLUE);
gridLayout.addView(customRectWithText);
// second custom view
CustomRectWithText customRectWithText1 = new CustomRectWithText(this);
customRectWithText1.setRectEndX(400);
customRectWithText1.setRectEndY(200);
customRectWithText1.setRectStartX(200 + 5);
customRectWithText1.setRectStartY(2);
customRectWithText1.setTileTitleText("Text 1");
customRectWithText1.setRectFillColor(Color.GREEN);
gridLayout.addView(customRectWithText1);
setContentView(gridLayout);
}
But still I am not getting both of the rectangles in a grid view. Only one rectangle is displayed at a time. In above case only first custom view is displayed.
Where am I doing wrong.
All I want is to make a repetitive rectangle of varying labels of any size inside a grid view.
Is this the way to do it. I mean is there any other way around.
I dont want to use ListItems.

Sorry but i do not have enough repo to comment.
But why dont you make an adapter?
Gridview behaves same as listView.
Use adapter to fill your grid.
This is the proper way to populate listView and gridView also.

Related

RecycleView adapter and main code is not working by an unknown mistake, can you spot the diffrence

hello everyone, I am kind of new using android studio and I am working on my school project. I need to use RecycleVie wand I tried making it but without success.
I use a Object class caled Task whcih have 3 propeties to be shown on the layout but I don't know where is my mistake. the rows which shown as problems are in bold. I will be glad if anyone can help me!
my Object class:
public class Task {
private String material;
private String day;
private String month;
public Task (String material,String day,String month)
{
this.material = material;
this.day = day;
this.month = month;
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
}
the Adapter Code:
public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<HomeRecyclerViewAdapter.ViewHolder> {
private Context mCtx;
private List<Task> tList;
// data is passed into the constructor
public HomeRecyclerViewAdapter(Context mCtx, List<Task> tList) {
this.mCtx = mCtx;
this.tList = tList;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvText, tvDateDay, tvDateMonth;
public ViewHolder(View itemView) {
super(itemView);
tvText = itemView.findViewById(R.id.tvText);
tvDateDay = itemView.findViewById(R.id.tvDateDay);
tvDateMonth = itemView.findViewById(R.id.tvDateMonth);
}
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.home_recyclerview_row, null);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Task task = tList.get(position);
**holder.tvText.setText(task.getMaterial());**
}
// allows clicks events to be caught
#Override
public int getItemCount() {
return tList.size();
}
}
and the main code:
public class HomeScreen_activity extends AppCompatActivity implements View.OnClickListener {
List<Task> tList;
RecyclerView homercy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.home_screen_layout);
homercy = (RecyclerView) findViewById(R.id.homercy);
homercy.setHasFixedSize(true);
homercy.setLayoutManager(new LinearLayoutManager(this));
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.homercy);
tList = new ArrayList<Task>();
Task t1 = new Task("test","12","05");
tList.add(t1);
**HomeRecyclerViewAdapter adapter = new HomeRecyclerViewAdapter(this,tList);**
recyclerView.setAdapter(adapter);
}
Maybe in onCreateViewHolder(), you must do this:
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_recyclerview_row, parent, false);
return new ViewHolder(view);
}

can't call adapter.getFilter() after setup recyclerview with filterable

I've use Filterable inside my RecyclerView. What I wanted to do is, to filter the recyclerview from edittext. Below is my actual code.
public class NavDrawerAdapter_v2 extends RecyclerView.Adapter<NavDrawerAdapter_v2.ViewHolder> implements Filterable{
private static final int TYPE_ITEM = 0;
private ArrayList<String> menu_list;
private ArrayList<String> filtered_menu_list;
Context mContext;
public static class ViewHolder extends RecyclerView.ViewHolder {
int Holderid;
TextView shopName, shopLevel;
public ViewHolder(View itemView,int ViewType) {
super(itemView);
shopName = (TextView) itemView.findViewById(R.id.rowText);
shopLevel = (TextView) itemView.findViewById(R.id.rowLevel);
if(ViewType == TYPE_ITEM) {
Holderid = 0;
}
}
}
public NavDrawerAdapter_v2(Context mContext, ArrayList<String> menu_list){
this.menu_list = menu_list;
this.filtered_menu_list = menu_list;
this.mContext = mContext;
}
#Override
public NavDrawerAdapter_v2.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_item_row,parent,false); //Inflating the layout
return new ViewHolder(v,viewType);
}
return null;
}
#Override
public void onBindViewHolder(NavDrawerAdapter_v2.ViewHolder holder, int position) {
if (holder.Holderid == 0) {
String getShopName = menu_list.get(position).split("-")[0];
String getShopLevel = menu_list.get(position).split("-")[1];
holder.shopName.setText(getShopName);
holder.shopLevel.setText(getShopLevel);
}
}
#Override
public int getItemCount() {
return menu_list == null ? 0 : menu_list.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemViewType(int position) {
return TYPE_ITEM;
}
public boolean okay(){
return true;
}
#Override
public Filter getFilter() {
return new UserFilter(this, menu_list);
}
private static class UserFilter extends Filter {
private final NavDrawerAdapter_v2 adapter;
private final ArrayList<String> originalList;
private final ArrayList<String> filteredList;
private UserFilter(NavDrawerAdapter_v2 adapter, ArrayList<String>originalList) {
super();
this.adapter = adapter;
this.originalList = new ArrayList<>(originalList);
this.filteredList = new ArrayList<>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredList.addAll(originalList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (String getValue : originalList) {
if (getValue.contains(filterPattern)) {
filteredList.add(getValue);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.filtered_menu_list.clear();
adapter.filtered_menu_list.addAll((ArrayList<String>) results.values);
adapter.notifyDataSetChanged();
}
}
}
But, in my fragment. I can't call adapter.getFilter(). What is wrong here?
If you want EditText for searchView purposes, you need to add change listener for EditText, as explained in the link : android on Text Change Listener
When the text changed, you should call
adapter.getFilter().filter(newText);
Alternatively, you should try to implement searchview in action bar with recyclerView. Todo this, implement getFilter() method inside your RecyclerView adapter. You can use the getFilter() method implemented in the link https://stackoverflow.com/a/10532898/1308990 .
menu.xml:
<item android:id="#+id/menuSearch"
android:title="search"
android:icon = "#android:drawable/ic_menu_search"
app:actionViewClass = "android.support.v7.widget.SearchView"
app:showAsAction = "always|collapseActionView"></item>
Inside onCreateOptionsMenu() method, write following codes :
MenuItem item = menu.findItem(R.id.menuSearch);
//SearchView searchView = (SearchView) item.getActionView();
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//Called when the query text is changed by the user.
#Override
public boolean onQueryTextChange(String newText) {
Log.d("soda in MainActivity","onQueryTextChange method is called.");
mutfagimFragment.adapter.getFilter().filter(newText);
return false;
}
});
When the user changes the text, check whether the onQueryTextChange() method is called by monitoring the logs. If it is not called, try to put the above codes inside onPrepareOptionsMenu() method rather than onCreateOptionsMenu() method.
Following your example, I'm pretty sure you were assigning the object to a RecyclerView.Adapter variable instead of to a NavDrawerAdapter_v2 variable inside the Activity.
RecyclerView.Adapter adapter = new NavDrawerAdapter_v2(menuList);
instead of
NavDrawerAdapter_v2 adapter = new NavDrawerAdapter_v2(menuList);
NavDrawerAdapter_v2 extends from RecyclerView.Adapter but at the same time implements Filterable.
If you assign the object to a RecyclerView.Adapter variable you will still be able to call getItemCount(), onBindViewHolder() and onCreateViewHolder() (since they are abstract methods from RecyclerView.Adapter)
The bad part is that you won't be able to call getFilter() because it belongs to the Filterable interface.

JavaFX typewriter effect for label

i have some problem with this method. it works fine, but with one little problem. there is too little time among i call this method. so only the last String is printed on a label. but i want that the next String starting printed, only after previous String is finished.
Sorry for my English((
public void some(final String s) {
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(2000));
}
protected void interpolate(double frac) {
final int length = s.length();
final int n = Math.round(length * (float) frac);
javafx.application.Platform.runLater(new Runnable() {
#Override
public void run() {
status.setValue(s.substring(0, n));
}
}
);
}
};
animation.play();
}
Use the following code to get a typewriting effect.
public void AnimateText(Label lbl, String descImp) {
String content = descImp;
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(2000));
}
protected void interpolate(double frac) {
final int length = content.length();
final int n = Math.round(length * (float) frac);
lbl.setText(content.substring(0, n));
}
};
animation.play();
}
I don't know if it is an effect that you are trying to achieve, but I have created (ugly) demo how you can do this with TimeLine
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
IntegerProperty letters= new SimpleIntegerProperty(0);
Label label = new Label();
Button animate = new Button("animate");
letters.addListener((a, b, c) -> {
label.setText("animate".substring(0, c.intValue()));
});
animate.setOnAction((e)->{
Timeline timeline = new Timeline();
KeyValue kv = new KeyValue(letters, "animate".length());
KeyFrame kf = new KeyFrame(Duration.seconds(3), kv);
timeline.getKeyFrames().add(kf);
timeline.play();
});
BorderPane pane = new BorderPane(label, null, null, animate, null);
primaryStage.setScene(new Scene(pane, 300,300));
primaryStage.show();
}
}

JavaFx ProgressBar Bind SimpleDoubleProperty

I am using a progressbar in a tableview, where I'm using bind on his property so that when the value is changed, progressbar is started:
private SimpleDoubleProperty progressBar;
public Tabela(Double progressBar) {
this.progressBar = new SimpleDoubleProperty(progressBar);
}
public Double getProgressBar() {
return progressBar.get();
}
public DoubleProperty getProgressBarProperty() {
return progressBar;
}
public void setProgressBar(Double progressBar) {
this.progressBar.set(progressBar);
}
public void setProgressBar(SimpleDoubleProperty progressBar) {
this.progressBar = progressBar;
}
And in my Hbox am using progressbar as follows:
final ProgressBar progress = new ProgressBar();
progress.setMinWidth(324.0);
progress.progressProperty().bind(tabela.getProgressBarProperty());
So I'm using a so that after a certain time the value is changed, ie I will control the progressbar. The value is changed, but in my tableview nothing happens, but when I change the column position to another, the progressbar is running.
The same happens with "label", i changed for "text" and it work, but if the progressbar I have to use.
have a way to force the 'tableview' refresh?
You need to follow the JavaFX naming standard to get TableViews and other widgets to properly refresh when an observable object changes. For instance, you should rename getProgressBarProperty() to progressBarProperty().
See: How to update TableView Row using javaFx
There would be something wrong in this source?
class table
...
public Tabela(String nome, Double progressBar, String etapa) {
this.nome = nome;
this.progressBar = new SimpleDoubleProperty(progressBar);
this.etapa = new SimpleStringProperty(etapa);
}
....
Add new line.
private void preencheListaNomeTabelas() {
getLista().add(new Tabela("Test", 0.0, "Test Text"));
Add hbox in table.
columTabela.setCellValueFactory(new PropertyValueFactory<Tabela, String>("nome"));
columSituacao.setCellFactory(new Callback<TableColumn<Tabela, Double>, TableCell<Tabela, Double>>() {
public TableCell<Tabela, Double> call(TableColumn<Tabela, Double> p) {
final HBox box = new HBox();
box.setPrefHeight(25.0);
final ProgressBar progressBar = new ProgressBar(-1);
final Text text = new Text();
**text.textProperty().bind(..); //I would use here the**
BorderPane border = new BorderPane();
border.setTop(text);
border.setBottom(progressBar);
BorderPane.setAlignment(text, Pos.CENTER);
box.getChildren().add(border);
final TableCell cell = new TableCell<Tabela, Double>() {
#Override
protected void updateItem(Double t, boolean bln) {
super.updateItem(t, bln);
if (bln) {
setText(null);
setGraphic(null);
} else {
progressBar.setProgress(t);
progressBar.prefWidthProperty().bind(this.widthProperty());
setGraphic(box);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
};
cell.setAlignment(Pos.CENTER);
return cell;
}
});
columSituacao.setCellValueFactory(new PropertyValueFactory<Tabela, Double>("progress"));
columSituacao.setText("Progresso");
tableView.getItems().addAll(lista);
tableView.getSelectionModel().selectFirst();
task
Task t = new Task() {
#Override
protected Object call() throws Exception {
Thread.sleep(10000);
getLista().get(0).setEtapa("Lendo PostgreSQL");
getLista().get(0).setProgressBar(-1.0);
return null;
}
};
new Thread(t).start();

Cannot properly set visible component

I'm trying to implement Menu with select box which sets to display or not component. I have this checkbox:
final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation");
toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
DataTabs.renderTab = toolbarSubMenuNavigation.isSelected();
// call here the getter setter and send boolean flag
System.out.println("subsystem1 #1 Enabled!");
}
});
And I have this tabpane which I want to render only if I have selected the checkbox:
public static boolean renderTab;
public DataTabs()
{
}
public boolean isRenderTab()
{
return renderTab;
}
public void setRenderTab(boolean renderTab)
{
this.renderTab = renderTab;
}
// below this code
tabPane.setVisible(renderTab);
When I run the code it's not working. I also tested this:
DataTabs tabs = new DataTabs(); // instantiate first
tabs.setRenderTab(toolbarSubMenuNavigation.isSelected());
public static boolean renderTab;
TabPane tabPane = new TabPane();
public DataTabs()
{
}
public boolean isRenderTab()
{
return renderTab;
}
public void setRenderTab(boolean renderTab)
{
tabPane.setVisible(renderTab);
}
But again there is no result when I run the code and I check or uncheck the checkbox.
This is the complete source code:
http://pastebin.com/tkj4Fby1
Maybe I need to add listener or something else which I'm missing?
EDIT
Test 3
I also tested this code:
final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation");
toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
DataTabs.toolbarSubMenuNavigation = toolbarSubMenuNavigation;
// call here the getter setter and send boolean flag
System.out.println("subsystem1 #1 Enabled!");
}
});
// class with tabs
public static CheckMenuItem toolbarSubMenuNavigation;
public static CheckMenuItem getToolbarSubMenuNavigation()
{
return toolbarSubMenuNavigation;
}
public static void setToolbarSubMenuNavigation(CheckMenuItem toolbarSubMenuNavigation)
{
DataTabs.toolbarSubMenuNavigation = toolbarSubMenuNavigation;
}
// below
abPane.visibleProperty().bind(toolbarSubMenuNavigation.selectedProperty());
I get NPE when I run the code.
You can easely tell to your tab to be visible when you check the box in one line
yourTab.visibleProperty().bind(yourCheckBox.selectedProperty());
And just with this line your tabpane will be visible only when it's checked

Resources